package classign.election.kingvar.come.electionclasssign.tools.views;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.text.Html;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.FileAsyncHttpResponseHandler;

import org.apache.http.Header;

import java.io.File;
import java.io.IOException;

import classign.election.kingvar.come.electionclasssign.R;
import classign.election.kingvar.come.electionclasssign.activity.MyApplication;

public class CustomShowDialog extends Dialog {
	private static final String TAG = "CustomShowDialog";
	private Button mPositiveBut;//确定
	private Button mNegativeBut;//取消
	private static TextView dialog_hint_message_tv;
	private TextView dailog_title;
	private static ProgressBar dialog_progressBar;
	private static Context context;

	public CustomShowDialog(Context context) {
		super(context, R.style.UpdateDialog);
		this.context = context;
		setCustomView();
	}

	public CustomShowDialog(Context context, boolean cancelable,
                            OnCancelListener cancelListener) {
		super(context, R.style.UpdateDialog);
		this.setCancelable(cancelable);
		this.setOnCancelListener(cancelListener);
		this.context = context;
		setCustomView();
	}

	public CustomShowDialog(Context context, int theme) {
		super(context, R.style.UpdateDialog);
		this.context = context;
		setCustomView();
	}

	/** 修改msg */
	public void setMsgHintText(String msg) {
		dialog_hint_message_tv.setText(Html.fromHtml(msg));

	}

	/** 修改确定按钮上的文字 */
	public void setPositiveText(String post) {
		mPositiveBut.setText(post);
	}

	/** 修改取消按钮上的文字 */
	public void setNegativeText(String nega) {
		mNegativeBut.setText(nega);
	}

	public void setDialogTitle(String nega) {
		dailog_title.setText(nega);
	}

	private void setCustomView() {
		View mView = LayoutInflater.from(getContext()).inflate(
				R.layout.custom_dialog, null);
		mNegativeBut = (Button) mView.findViewById(R.id.dialog_cancle_but);
		mPositiveBut = (Button) mView.findViewById(R.id.dialog_sure_but);
		dialog_hint_message_tv = (TextView) mView.findViewById(R.id.dialog_hint_message_tv);
		dailog_title = (TextView) mView.findViewById(R.id.dailog_title);
		dialog_progressBar = (ProgressBar) mView.findViewById(R.id.dialog_progressbar);
		dialog_progressBar.setVisibility(View.GONE);
		mView.setBackgroundResource(R.drawable.bg_d_rect_border);
		super.setContentView(mView);
	}

	@Override
	public void setCanceledOnTouchOutside(boolean cancel) {
		super.setCanceledOnTouchOutside(cancel);
	}

	@Override
	public void setContentView(int layoutResID) {
		super.setContentView(layoutResID);
	}

	public void setOnPositiveListener(View.OnClickListener listener) {
		mPositiveBut.setOnClickListener(listener);
	}

	public void setOnNegativeListener(View.OnClickListener listener) {
		mNegativeBut.setOnClickListener(listener);
	}

	public static void ShowCustomDialog(final Activity context, String msg,
			final String url, int uptate) {
		final CustomShowDialog dialog = new CustomShowDialog(context);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setMsgHintText(msg);
		dialog.setOnPositiveListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.setOnPositiveListener(null);
				dialog.setOnNegativeListener(null);
				downLoadApk(dialog, url);
				//查看文件是否存在
				System.out.println(url);
			}
		});

		if (uptate == 0) {
			dialog.setOnNegativeListener(new View.OnClickListener() {//看看再说
				@Override
				public void onClick(View v) {
					dialog.dismiss();
				}
			});
		}

		if (uptate == 1) {
			dialog.setCancelable(false);
		}

		LayoutParams lay = dialog.getWindow().getAttributes();
		DisplayMetrics dm = new DisplayMetrics();//获取屏幕分辨率
		context.getWindowManager().getDefaultDisplay().getMetrics(dm);//
		Rect rect = new Rect();
		View view = context.getWindow().getDecorView();
		view.getWindowVisibleDisplayFrame(rect);
		lay.width = dm.widthPixels * 9 / 10;
		dialog.show();

	}

	private static void downLoadApk(final Dialog dialog, String url) {
		File file = new File(MyApplication.getInstance().getFilesDir()
				.getAbsolutePath() + File.separator + "ElectionClassSign.apk");
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		AsyncHttpClient client = new AsyncHttpClient(true, 80, 443);
		client.get(url, new FileAsyncHttpResponseHandler(file) {
			@Override
			public void onProgress(long bytesWritten, long totalSize) {
				int total = (int) (bytesWritten * 1.0 / totalSize * 100);
				dialog_hint_message_tv.setText("" + total + "%");
				dialog_progressBar.setVisibility(View.VISIBLE);
				dialog_progressBar.setProgress(total);
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, File arg2) {
				dialog.dismiss();
				installApk(context);
			}

			@Override
			public void onFailure(int arg0, Header[] arg1, Throwable arg2,
					File arg3) {
				dialog.dismiss();
			}
		});
	}

	/**
	 * 安装apk
	 */
	private static void installApk(Context context) {
		//		File file = new File(StorageUtils.YR_CAMERA_DIR + "JinwawaForTeacher.apk");
		File file = new File(MyApplication.getInstance().getFilesDir()
				.getAbsolutePath() + File.separator + "ElectionClassSign.apk");
		if (!file.exists()) {
			return;
		}
		String command = "chmod  777 " + file.getAbsolutePath();
		Runtime runtime = Runtime.getRuntime();
		try {
			runtime.exec(command);
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");
		context.startActivity(intent);
	}
}
